package com.cdtu.labpreview.util;

import com.cdtu.labpreview.common.SystemConstants;
import com.cdtu.labpreview.common.UserHolder;
import com.cdtu.labpreview.dto.UserDTO;
import com.cdtu.labpreview.entity.Admin;
import com.cdtu.labpreview.entity.Student;
import com.cdtu.labpreview.entity.Teacher;
import com.cdtu.labpreview.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * 登录拦截器，判断用户是否登录
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //设置响应头，解决前后端分离存在的跨域问题
        if(response.getHeader("Access-Control-Allow-Origin")==null||
                response.getHeader("Access-Control-Allow-Origin")=="")
        response.addHeader(  "Access-Control-Allow-Origin","http://localhost:8081");//允许所有来源访同

        if(response.getHeader("Access-Control-Allow-Methods")==null||
                response.getHeader("Access-Control-Allow-Methods")=="")
        response.addHeader(  "Access-Control-Allow-Methods","POST, PUT, PATCH, GET, DELETE, OPTIONS");//允许访问的方式

        if(response.getHeader("Access-Control-Allow-Credentials")==null||
                response.getHeader("Access-Control-Allow-Credentials")=="")
        response.addHeader("Access-Control-Allow-Credentials", "true");

        if(response.getHeader("Access-Control-Allow-Headers")==null||
                response.getHeader("Access-Control-Allow-Headers")=="")
            response.addHeader("Access-Control-Allow-Headers","Origin, X-Api-Key, X-Requested-With, Content-Type, Accept, Authorization");
        //登录请求直接放行
        String requestURL = request.getRequestURL().toString();
        if(requestURL.equals("http://localhost:8080/user/login")||
                requestURL.equals("http://localhost:8080/common/upload")||
                requestURL.equals("http://localhost:8080/common/download")
        )
        {
            return true;
        }
        //预检请求直接设置200 ok
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        //1.获取session
        request.getHeader("cookie");
        Cookie[] cookies = request.getCookies();
        String sessionId =null;
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals("sessionId")){
                String value = cookie.getValue();
                sessionId=value;
            }
        }

        System.out.println("sessionId2:"+sessionId);
        HttpSession session = request.getSession();
        //2.获取session中的用户
        Object o = session.getAttribute("user" + sessionId);
        if(o==null){
            response.setStatus(401);
            log.info("请先进行登录！");
            return false;
        }
        //3.判断用户类型
        UserDTO u=new UserDTO();
        if(o instanceof Student){
            Student student=(Student) o;
            u.setUserNo(student.getSno());
            u.setName(student.getName());
            u.setType(1);
        }else if (o instanceof Teacher){
            Teacher teacher=(Teacher) o;
            u.setUserNo(teacher.getTno());
            u.setName(teacher.getName());
            u.setType(2);
        }else{
            Admin admin=(Admin) o;
            u.setUserNo(admin.getAno());
            u.setName(admin.getName());
            u.setType(0);
        }
        //4.存在保存到ThreadLocal
        UserHolder.saveUser(u);
        //5.放行
        return true;
    }
}
